package com.artisan.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;

/**
 * Created by  on 2016/4/12.
 * 发送手机验证码
 */
public class SendPhone {
    public static String getVerifyCode(final String phone,final String code){
        String returnStr = null;

        try {
            StringBuffer sb = new StringBuffer("http://sms.1xinxi.cn/asmx/smsservice.aspx?");

            sb.append("name=");

            sb.append("&pwd=");

            sb.append("&mobile="+phone);

            sb.append("&content="+ URLEncoder.encode(code,"UTF-8"));

            sb.append("&stime=");

            sb.append("&sign=");

            sb.append("&type=pt&extno=2");
            System.out.println("sb:"+sb.toString());
            URL url = new URL(sb.toString());

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");

            InputStream is =url.openStream();

            returnStr = convertStreamToString(is);

            System.out.println(returnStr);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IOException 异常：" +e.getMessage());
        }
        return returnStr;
    }
    /**
     * 转换返回值类型为UTF-8格式.
     * @param is
     * @return
     */
    public static String convertStreamToString(InputStream is) {
        StringBuilder sb1 = new StringBuilder();
        byte[] bytes = new byte[4096];
        int size = 0;

        try {
            while ((size = is.read(bytes)) > 0) {
                String str = new String(bytes, 0, size, "UTF-8");
                sb1.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb1.toString();
    }
    public static String toUtf8(String str) throws UnsupportedEncodingException {
        return new String(str.getBytes("UTF-8"),"UTF-8");
    }

    public static void main(String args[])throws  Exception{
        System.out.print("resutlt is :"+getVerifyCode("13776616105","4526"));
    }
}
